package com.laundry.controller;

import com.laundry.dto.ApiResponse;
import com.laundry.entity.UserAddress;
import com.laundry.service.UserAddressService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/user/addresses")
@RequiredArgsConstructor
public class UserAddressController {
    
    private final UserAddressService addressService;
    
    @GetMapping
    public ApiResponse<List<UserAddress>> getUserAddresses() {
        try {
            List<UserAddress> addresses = addressService.getUserAddresses();
            return ApiResponse.success(addresses);
        } catch (Exception e) {
            return ApiResponse.error("获取地址列表失败: " + e.getMessage());
        }
    }
    
    @PostMapping
    public ApiResponse<UserAddress> addAddress(@Valid @RequestBody UserAddress address) {
        try {
            UserAddress savedAddress = addressService.addAddress(address);
            return ApiResponse.success("地址添加成功", savedAddress);
        } catch (Exception e) {
            return ApiResponse.error("添加地址失败: " + e.getMessage());
        }
    }
    
    @GetMapping("/{id}")
    public ApiResponse<UserAddress> getAddressById(@PathVariable Long id) {
        try {
            UserAddress address = addressService.getAddressById(id);
            return ApiResponse.success(address);
        } catch (Exception e) {
            return ApiResponse.error("获取地址详情失败: " + e.getMessage());
        }
    }
    
    @PutMapping("/{id}")
    public ApiResponse<UserAddress> updateAddress(@PathVariable Long id, @Valid @RequestBody UserAddress address) {
        try {
            UserAddress updatedAddress = addressService.updateAddress(id, address);
            return ApiResponse.success("地址更新成功", updatedAddress);
        } catch (Exception e) {
            return ApiResponse.error("更新地址失败: " + e.getMessage());
        }
    }
    
    @DeleteMapping("/{id}")
    public ApiResponse<Void> deleteAddress(@PathVariable Long id) {
        try {
            addressService.deleteAddress(id);
            return ApiResponse.success("地址删除成功");
        } catch (Exception e) {
            return ApiResponse.error("删除地址失败: " + e.getMessage());
        }
    }
    
    @PutMapping("/{id}/default")
    public ApiResponse<UserAddress> setDefaultAddress(@PathVariable Long id) {
        try {
            UserAddress address = addressService.setDefaultAddress(id);
            return ApiResponse.success("默认地址设置成功", address);
        } catch (Exception e) {
            return ApiResponse.error("设置默认地址失败: " + e.getMessage());
        }
    }
}
